import CryptoJS from "crypto-js";

const PASSPHRASE = import.meta.env.VITE_AES_PASSPHRASE as string;

if (!PASSPHRASE) {
  throw new Error("请在 .env.local 中配置 VITE_AES_PASSPHRASE");
}

/* ---------- 工具类 ---------- */
export class AESUtil {
  private static readonly KEY_SIZE = 256 / 32;
  private static readonly IV_SIZE = 128 / 8;
  private static readonly SALT_SIZE = 128 / 8;
  private static readonly ITERATIONS = 10000;

  /** 加密 */
  static encrypt(plainText: string): string {
    const salt = CryptoJS.lib.WordArray.random(this.SALT_SIZE);
    const iv = CryptoJS.lib.WordArray.random(this.IV_SIZE);

    const key = CryptoJS.PBKDF2(PASSPHRASE, salt, {
      keySize: this.KEY_SIZE,
      iterations: this.ITERATIONS,
    });

    const encrypted = CryptoJS.AES.encrypt(plainText, key, { iv }).toString();

    // 拼接：salt|iv|ciphertext，全部 base64
    return [salt.toString(), iv.toString(), encrypted].join("|");
  }

  /** 解密 */
  static decrypt(combined: string): string {
    const [saltStr, ivStr, cipherText] = combined.split("|");
    if (!saltStr || !ivStr || !cipherText) throw new Error("格式错误");

    const salt = CryptoJS.enc.Hex.parse(saltStr);
    const iv = CryptoJS.enc.Hex.parse(ivStr);

    const key = CryptoJS.PBKDF2(PASSPHRASE, salt, {
      keySize: this.KEY_SIZE,
      iterations: this.ITERATIONS,
    });

    const bytes = CryptoJS.AES.decrypt(cipherText, key, { iv });
    const plain = bytes.toString(CryptoJS.enc.Utf8);
    if (!plain) throw new Error("解密失败");
    return plain;
  }
}
